package client

import (
	"chess_platform/controllers"
	. "chess_platform/internal/common"
	"chess_platform/internal/token"
	"encoding/json"
	"fmt"
)

type BaseUserInfo struct {
	Uid               int64
	InitialLoginToday int64
}

type BaseController struct {
	controllers.BaseController
	BaseUserInfo
}

type GrantController struct {
	BaseController
}

func (b *BaseController) Prepare() {
	b.Res = new(controllers.Response)
	LogClient.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogClient.Debug(fmt.Sprintf("用户访问(ID:%v)url:%v", b.Uid, b.Ctx.Input.URL()))
}

func (b *BaseController) Finish() {
	data, _ := json.Marshal(b.Data["json"])
	LogClient.Debug(fmt.Sprintf("用户(ID:%v)访问url:%v返回值:%v", b.Uid, b.Ctx.Input.URL(), string(data)))
}

func (b *GrantController) Prepare() {
	LogClient.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogClient.Debug("用户访问url:" + b.Ctx.Input.URL())
	b.Res = new(controllers.Response)
	var t controllers.Token
	err := b.Unmarshal(&t)
	if err != nil {
		b.DecodeParamsError(err)
		return
	}
	ex, err := token.Parse(t.Token)
	if err != nil || ex.GetTokenType() != TokenClient {
		LogClient.Error(fmt.Sprintf("token解析错误:%v,或不是此Client类型的token", err))
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}

	b.Uid = ex.GetId()
	LogClient.Debug(fmt.Sprintf("用户访问(ID:%v)url:%v", b.Uid, b.Ctx.Input.URL()))

	info, _ := ex.GetInfo().(float64)
	b.InitialLoginToday = int64(info)

	keyAccessLimit := fmt.Sprintf("ClientUserLimit-%v", b.Uid)
	if !AccessLimit(keyAccessLimit, Al.Frequency, Al.ExpireTime) {
		b.ResponseFail("操作过于频繁，请稍候再操作")
		return
	}
	if ex.IsExpire() {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserExpire
		b.Response()
		return
	}
	/*
		//cache里不存在说明token已经过期了
		key := fmt.Sprintf("%v%v", KeyClientTokenCache, b.Uid)
		if ex.IsExpire() || !RedisCache.IsExist(key) {
			b.Res.Code = ErrUserUnauthorized
			b.Res.Msg = MsgErrUserExpire
			b.Response()
			return
		}

		//cache里的token与传进来的不一样的话表示此帐号在其它地方登录了
		tokenCache := RedisCache.GetString(key)
		if tokenCache != "" { //token在缓存里存在
			deviceIdKey := fmt.Sprintf("%v%v", KeyClientDeviceId, b.Uid)
			deviceId := RedisCache.GetString(deviceIdKey)
			if tokenCache != t.Token && t.DeviceId != deviceId {
				LogClient.Debug(fmt.Sprintf("玩家(ID:%v)缓存里的token:%v,device_id:%v\n,用户传过来的token:%v,device_id:%v",
					b.Uid, tokenCache, deviceId, t.Token, t.DeviceId))
				b.Res.Code = ErrClientAlreadyLogin
				b.Res.Msg = MsgErrAlreadyLogin
				b.Response()
				return
			}
		} else { //不存在
			b.Res.Code = ErrUserUnauthorized
			b.Res.Msg = MsgErrUserUnauthorized
			b.Response()
			return
		}
	*/
}
